package com.agent.crm.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.os.SystemClock;

import com.agent.crm.sechdule.receiver.RepeatingAlarm;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleVO;

public class SechduleMainService extends Service {

	private PendingIntent mAlarmSender;
	private ScheduleDAO dao = null;
	private SharedPreferences preferences ;
	private Editor editor;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
//		 mAlarmSender = PendingIntent.getService(SechduleMainService.this,
//	                0, new Intent(SechduleMainService.this, AlarmService_Service.class), 0);
//		 long firstTime = SystemClock.elapsedRealtime();
//
//         // Schedule the alarm!
//         AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//         am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//                         firstTime, 30*1000, mAlarmSender);
//
//         // Tell the user about what we did.
//         Toast.makeText(SechduleMainService.this, "开始任务提醒",
//                 Toast.LENGTH_LONG).show();
//         //停止service
//         // And cancel the alarm.
//         AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//         am.cancel(mAlarmSender);
//
//         // Tell the user about what we did.
//         Toast.makeText(AlarmService.this, R.string.repeating_unscheduled,
//                 Toast.LENGTH_LONG).show();
		preferences=getSharedPreferences("ScheduleTask", Context.MODE_PRIVATE);
		dao = new ScheduleDAO(this);
		dao.resetAllRunningScheduleWhenServiceStart("remind");
		Thread startThread = new Thread(mSchduleStartTask);
		startThread.start();
//        Thread stopThread = new Thread(mSchduleStopTask);
//        stopThread.start();
	}
	
	Runnable mSchduleStartTask = new Runnable() {
        public void run() {
            // Normally we would do some work here...  for our sample, we will
            // just sleep for 30 seconds.
        	while(true){
        		List<ScheduleVO> schedules = dao.getAllScheduleWithOperationRemind();
        		Date d=new Date();
        		Calendar comparetor= Calendar.getInstance();
        		comparetor.setTime(d);
        		comparetor.set(Calendar.MINUTE, comparetor.get(Calendar.MINUTE)+10);
        		for (int i = 0; i < schedules.size(); i++) {
        			if( "M".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())||
        				"Y".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())){
        				continue;
        			}
        			if(comparetor.before(formatStringToDate(schedules.get(i).getScheduleStartDate()))){
        				continue;
        			}
        			Intent intent = new Intent(SechduleMainService.this, RepeatingAlarm.class);
        			intent.putExtra("title", schedules.get(i).getScheduleTitle());
        			intent.putExtra("schedule", schedules.get(i));
                    
        			PendingIntent sender = PendingIntent.getBroadcast(SechduleMainService.this,
                    		schedules.get(i).getScheduleID(), intent, 0);
                    
                    // We want the alarm to go off 30 seconds from now.
                    long firstTime = SystemClock.elapsedRealtime();
//                    firstTime += 15*1000;
                    // Schedule the alarm!
                    Calendar c= Calendar.getInstance();
                    c.clear();
                    c.setTime(formatStringToDate(schedules.get(i).getScheduleStartDate()));
                    TimeZone tz = TimeZone.getTimeZone("GMT");        
                    c.setTimeZone(tz); 
                    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
                    if("1".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())){
                    	//执行一次的任务
                    	am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), sender);
//                    	dao.resetScheduleStatusFlags(schedules.get(i).getScheduleID(),"1");
                    }else if("D".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())){
                    	am.setRepeating(AlarmManager.RTC_WAKEUP,
                    			c.getTimeInMillis(),24*60*60*1000, sender);
                    }else if("W".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())){
                    	am.setRepeating(AlarmManager.RTC_WAKEUP,
                    			c.getTimeInMillis(),7*24*60*60*1000, sender);
                    }else{
                    	//循环任务
                    	am.setRepeating(AlarmManager.RTC_WAKEUP,
                    			c.getTimeInMillis(), Integer.valueOf(schedules.get(i).getScheduleCycleType())*60*1000, sender);
                    }
                    dao.resetScheduleStatusFlags(schedules.get(i).getScheduleID(),"1");
        		}
        		try {
    				Thread.sleep(60*1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}
        }
    };
	
    Runnable mSchduleStopTask = new Runnable() {
        public void run() {
            // Normally we would do some work here...  for our sample, we will
            // just sleep for 30 seconds.
        	try {
				Thread.sleep(120*1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	while(true){
        		List<ScheduleVO> schedules = dao.getAllScheduleInRuning();
        		Date d=new Date();
            	for (int i = 0; i < schedules.size(); i++) {
            		if("1".equalsIgnoreCase(schedules.get(i).getScheduleCycleType())){
	           			 dao.resetScheduleStatusFlags(schedules.get(i).getScheduleID(),"2");
	           			 continue;
           		    }
            		if(d.after(formatStringToDate(schedules.get(i).getScheduleEndDate()))){
            			Intent intent = new Intent(SechduleMainService.this,
            					RepeatingAlarm.class);
                		PendingIntent sender = PendingIntent.getBroadcast(SechduleMainService.this,
                        		schedules.get(i).getScheduleID(), intent, 0);
            			// And cancel the alarm.
            			AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            			am.cancel(sender);
            			dao.resetScheduleStatusFlagsToFinished(schedules.get(i).getScheduleID());
            		}
            	}
            	try {
    				Thread.sleep(60*1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        	}
        }
    };
    
    private Date formatStringToDate(String str){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			return format.parse(format.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Date();
	}
    
	private void writeSchduleFlagToXmlConfig(){
		
	};
	
	private void getSchduleFlagFromXmlConfig(){
		
	};

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}

	
}
